<template>
  <basic-container>
    <div class="customerfifter">
      <el-form :inline="true" :model="customerFrom" class="demo-form-inline">
        <el-form-item label="后台单号：">
          <el-input v-model.trim="customerFrom.xmbzNo" clearable size="small" placeholder="请输入后台单号" @keyup.enter.native='handleFilter(customerFrom,Launchdate)'></el-input>
        </el-form-item>
        <el-form-item label="平台单号：">
          <el-input v-model.trim="customerFrom.platformOrderId" clearable size="small" placeholder="请输入平台单号"
            @keyup.enter.native='handleFilter(customerFrom,Launchdate)'></el-input>
        </el-form-item>
        <el-form-item label="城市：">
          <el-select v-model="deptName" size="small" placeholder="请选择城市" @change="handleCity" ref='cityIdRef'
            @keydown.native="selectBlur($event)">
            <el-option v-for="item in cityList" :key="item.id" size="small" :label="item.deptName" :value="{label:item.deptName,value:item.id}">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类别:">
          <el-select v-model="channelTypeidName" clearable placeholder="请选择渠道类别" size="small" @visible-change="getchannelListType"
            @change="handleChannelTypeId" ref='channelTypeidNameRef' @keydown.native="selectBlur($event)">
            <el-option v-for="item in channelTypelist" :key="item.id" :label="item.channelName" :value="{label:item.id,value:item.channelKey,name:item.channelName}" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道：">
          <el-select v-model="customerFrom.channel" filterable clearable placeholder="渠道" size="small" @visible-change="getchannelList"
            ref='channelNameRef' @keydown.native="selectBlur($event)">
            <el-option v-for="item in channelList" :key="item.channelKey" :label="item.channelName" :value="item.channelKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
          <!--  <el-date-picker size="small" v-model="Launchdate" type="daterange" range-separator="至" start-placeholder="开始日期"
            :clearable='false' end-placeholder="结束日期">
          </el-date-picker> -->
          <el-date-picker v-model="Launchdate" type="datetimerange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"
            align="right" size="small" :clearable='false'>
          </el-date-picker>
        </el-form-item>

        <el-form-item label="失败原因类型：">
          <el-select v-model="customerFrom.failType" size="small" clearable placeholder="请选择失败原因类型" @visible-change="getfailTypeList"
            ref='failTypeRef' @keydown.native="selectBlur($event)">
            <el-option v-for="item in failTypeList" :key="item.dictKey" size="small" :label="item.dictValue" :value="item.dictKey">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" plain size="small" icon="el-icon-search" @click="handleFilter(customerFrom,Launchdate)">查询</el-button>
          <el-button type="success" plain size="small" icon="el-icon-download" @click="handleExport(customerFrom,Launchdate)">导出</el-button>
        </el-form-item>
        <el-form-item>
          <div style="color: red;font-size: 6px;font-weight: 500;padding-top: 6px;">注：导出时，最多导出5千条，数据不足时，重新选择时间</div>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="customerList" style="width: 100%" :default-sort="{prop: 'times'}" border>
      <el-table-column prop="xmbzNo" label="后台单号" width="100">
      </el-table-column>
      <el-table-column prop="platformOrderId" label="平台单号">
      </el-table-column>
      <el-table-column prop="deliveryTime" label="配送时间">
      </el-table-column>
      <el-table-column prop="orderTime" label="下单时间">
      </el-table-column>
      <el-table-column prop="channelTypeName" label="渠道类别">
      </el-table-column>
      <el-table-column prop="channelName" label="渠道" width="100">
      </el-table-column>
      <el-table-column prop="deptName" label="城市" width="80">
      </el-table-column>
      <el-table-column prop="failReason" label="失败原因" width="120" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="status" label="操作" width="80">
        <template slot-scope="scope">
          <span @click="handlerWacthorer(scope.$index, scope.row)">查看订单</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" layout="sizes,prev, pager, next,total" :page.sync="customerFrom.page"
      :limit.sync="customerFrom.size" @pagination="getList" />
  </basic-container>
</template>

<script>
  import {
    getOrderErrorDepts,
    OrderChannelTypeList,
    getOrderChannelLists,
    getautoconfirmLog,
    autolog
  } from "@/api/failure";
  import Pagination from "@/components/Pagination"; // 分页
  export default {
    components: {
      Pagination,
    },
    data() {
      return {
        customerFrom: {
          xmbzNo: '',
          platformOrderId: '',
          deptId: '',
          channelType: '', //渠道类型
          channel: '', //渠道
          failType: '',
          startTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 00:00:00")
            .toString(),
          endTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 23:59:59")
            .toString(),
          page: 1, //页码
          size: 10 //每页页码
        },
        tableKey: 0,
        total: 0,
        listLoading: true,
        customerList: [],
        Launchdate: [
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 23:59:59")
          .toString(),
        ],
        cityList: [],
        channelTypelist: [],
        failTypeList: [],
        channelList: [],
        deptName: '',
        channelTypeidIds: '',
        channelTypeidTypes: '',
        channelTypeidName: '',


      }
    },
    mounted() {
      this.getcityList();
      this.getchannelListType();
      setTimeout(() => {
        this.getList();
      }, 1.5 * 1000);
      window.addEventListener("keydown", this.keyupEnter);
    },
    destroyed() {
      window.removeEventListener("keydown", this.keyDown, false);
    },
    methods: {
      // 选择框回车失焦
      selectBlur(e) {
        if (e.keyCode == 13) {
          this.$refs['cityIdRef'].blur();
          this.$refs['channelTypeidNameRef'].blur();
          this.$refs['channelNameRef'].blur();
          this.$refs['failTypeRef'].blur();
          e.returnValue = false;
        }
      },

      keyupEnter() {
        if (window.event.keyCode == 13) {
          this.handleFilter(this.Launchdate); // 查询事件
        }
      },
      //如果页面有keep-alive缓存功能，这个函数会触发
      activated() {
        window.addEventListener("keydown", this.keyupEnter);
      },
      deactivated() {
        window.removeEventListener("keydown", this.keyupEnter);
      },
      // 城市
      getcityList() {
        getOrderErrorDepts('').then(res => {
          // res.data.data.unshift({
          //   id: 1,
          //   deptName: "全国"
          // })
          this.cityList = res.data.data;
          this.deptName = res.data.data[0].deptName;
          this.customerFrom.deptId = res.data.data[0].id;

        })

      },
      handleCity(data) {
        if (data) {
          this.deptName = data.label;
          this.customerFrom.deptId = data.value;
        }
      },
      getchannelListType() { //  渠道类别
        OrderChannelTypeList().then(res => {
          this.channelTypelist = res.data.data;
        })
        this.customerFrom.channelType = ''
      },
      getchannelList() {
        //渠道
        if (this.channelTypeidName == '') {
          this.$message({
            type: "warning",
            message: "请先选择渠道类别!"
          });
          return false

        } else {
          getOrderChannelLists({
            parentId: this.channelTypeidIds
          }).then(response => {
            this.channelList = response.data.data;
          });
        }
      },
      getfailTypeList() {
        autolog('').then(res => {
          this.failTypeList = res.data.data;
        })
      },
      handleChannelTypeId(data) {
        if (data) {
          this.channelTypeidIds = data.label;
          this.channelTypeidTypes = data.value;
          this.channelTypeidName = data.name;
        } else {
          this.customerFrom.channelType = '';
          this.channelTypeidTypes = '';
          this.channelTypeidName = '';

        }
      },
      getList() {
        //列表数据
        this.customerFrom.channelType = this.channelTypeidTypes;
        this.listLoading = true;
        getautoconfirmLog(this.customerFrom).then(response => {
          this.customerList = response.data.data.rows;
          this.total = response.data.data.total;
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },

      // 查询
      handleFilter(customerFrom, times) { //查询

        if (times == null) {
          this.customerFrom.startTime = null;
          this.customerFrom.endTime = null;

        } else if (times) {
          this.customerFrom.startTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD HH:mm:00")
            .toString();
          this.customerFrom.endTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD HH:mm:59")
            .toString();
        }
        var time1 = Date.parse(this.customerFrom.startTime);
        var time2 = Date.parse(this.customerFrom.endTime);
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 31) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          this.customerFrom.page = 1;
          this.getList();
        }

      },


      //导出
      handleExport(customerFrom, times) { //查询
        console.log(times, 'times')
        if (times == null) {
          this.$message({
            showClose: true,
            message: "请选择下单时间，再点击【导出】按钮",
            type: "warning"
          });
          return false;

        } else if (times) {
          this.customerFrom.startTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD HH:mm:00")
            .toString();
          this.customerFrom.endTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD HH:mm:59")
            .toString();
        }
        var time1 = Date.parse(this.customerFrom.startTime);
        var time2 = Date.parse(this.customerFrom.endTime);
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 31) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          var user = JSON.parse(localStorage.getItem('saber-userInfo'));
          this.customerFrom.channelType = this.channelTypeidTypes;
          if (customerFrom.channel == null) {
            customerFrom.channel = '';
          }
          if (customerFrom.failType == null) {
            customerFrom.failType = '';
          }
          window.open(
            `/api/xmbz-order/autoconfirmLog/downLoadLogExcel?xmbzNo=${customerFrom.xmbzNo}&platformOrderId=${customerFrom.platformOrderId}&channelType=${this.channelTypeidTypes}&channel=${customerFrom.channel}&failType=${customerFrom.failType}&deptId=${customerFrom.deptId}&startTime=${customerFrom.startTime}&endTime=${customerFrom.endTime}&blade-auth=bearer ${user['content'].accessToken}`

          )
          console.log(
            `/api/xmbz-order/autoconfirmLog/downLoadLogExcel?xmbzNo=${customerFrom.xmbzNo}&platformOrderId=${customerFrom.platformOrderId}&channelType=${this.channelTypeidTypes}&channel=${customerFrom.channel}&failType=${customerFrom.failType}&deptId=${customerFrom.deptId}&startTime=${customerFrom.startTime}&endTime=${customerFrom.endTime}&blade-auth=bearer ${user['content'].accessToken}`
          )
        }

      },
      // 查看
      handlerWacthorer(index, row) {
        let newUrl = this.$router.resolve({
          path: "/viewOrdInfor",
          query: {
            id: row.id,
          }
        });
        window.open(newUrl.href, "_blank");
      },

    }
  }
</script>


<style lang="scss">
  .customer {

    .customerfifter {}
  }
</style>
